import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const project = await db.project.findUnique({
      where: { id },
      include: {
        members: {
          include: {
            user: {
              select: {
                id: true,
                name: true,
                username: true,
                email: true
              }
            }
          }
        },
        iterations: {
          select: {
            id: true,
            name: true,
            status: true,
            startDate: true,
            endDate: true
          }
        },
        requirements: {
          include: {
            creator: {
              select: {
                name: true,
                username: true
              }
            },
            assignee: {
              select: {
                name: true,
                username: true
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        tasks: {
          include: {
            creator: {
              select: {
                name: true,
                username: true
              }
            },
            assignee: {
              select: {
                name: true,
                username: true
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        bugs: {
          include: {
            creator: {
              select: {
                name: true,
                username: true
              }
            },
            assignee: {
              select: {
                name: true,
                username: true
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        hardwareVersions: {
          include: {
            bom: {
              select: {
                id: true,
                version: true,
                name: true,
                status: true,
                totalCost: true
              }
            },
            documents: {
              include: {
                document: {
                  select: {
                    id: true,
                    name: true,
                    type: true,
                    version: true,
                    status: true,
                    filePath: true,
                    fileSize: true,
                    mimeType: true
                  }
                }
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        boms: {
          include: {
            items: {
              include: {
                component: {
                  select: {
                    id: true,
                    partNumber: true,
                    name: true,
                    category: true,
                    brand: true,
                    manufacturer: true,
                    specifications: true
                  }
                }
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        testCases: {
          include: {
            creator: {
              select: {
                name: true,
                username: true
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        // 硬件测试资料
        hardwareTests: {
          include: {
            tester: {
              select: {
                name: true,
                username: true
              }
            },
            hardwareVersion: {
              select: {
                id: true,
                version: true,
                name: true
              }
            },
            documents: {
              include: {
                document: {
                  select: {
                    id: true,
                    name: true,
                    type: true,
                    version: true,
                    status: true,
                    filePath: true,
                    fileSize: true,
                    mimeType: true
                  }
                }
              }
            },
            templates: {
              include: {
                template: {
                  select: {
                    id: true,
                    name: true,
                    type: true,
                    category: true,
                    version: true
                  }
                }
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        // 生产订单资料
        productionOrders: {
          include: {
            creator: {
              select: {
                name: true,
                username: true
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        // 质量报告资料
        qualityReports: {
          include: {
            productionOrder: {
              select: {
                id: true,
                orderNumber: true,
                version: true
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        // 附件资料
        attachments: {
          include: {
            uploader: {
              select: {
                name: true,
                username: true
              }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        _count: {
          select: {
            requirements: true,
            tasks: true,
            bugs: true,
            members: true,
            iterations: true,
            testCases: true,
            hardwareVersions: true,
            boms: true,
            comments: true,
            attachments: true,
            hardwareTests: true,
            productionOrders: true,
            qualityReports: true
          }
        }
      }
    })

    if (!project) {
      return NextResponse.json(
        { error: 'Project not found' },
        { status: 404 }
      )
    }

    return NextResponse.json(project)
  } catch (error) {
    console.error('Error fetching project:', error)
    return NextResponse.json(
      { error: 'Failed to fetch project' },
      { status: 500 }
    )
  }
}

export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const body = await request.json()
    const { name, key, description, type, status } = body

    if (!name || !key) {
      return NextResponse.json(
        { error: 'Missing required fields: name and key are required' },
        { status: 400 }
      )
    }

    // Check if project key already exists for other projects
    const existingProject = await db.project.findFirst({
      where: { 
        key: key,
        id: { not: id }
      }
    })

    if (existingProject) {
      return NextResponse.json(
        { error: 'Project with this key already exists' },
        { status: 400 }
      )
    }

    const project = await db.project.update({
      where: { id },
      data: {
        name,
        key,
        description,
        type,
        status
      },
      include: {
        _count: {
          select: {
            requirements: true,
            tasks: true,
            bugs: true,
            members: true
          }
        }
      }
    })

    return NextResponse.json(project)
  } catch (error) {
    console.error('Error updating project:', error)
    return NextResponse.json(
      { error: 'Failed to update project' },
      { status: 500 }
    )
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    await db.project.delete({
      where: { id }
    })

    return NextResponse.json({ message: 'Project deleted successfully' })
  } catch (error) {
    console.error('Error deleting project:', error)
    return NextResponse.json(
      { error: 'Failed to delete project' },
      { status: 500 }
    )
  }
}